package com.atguigu.tingshu.live.config;


import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.model.live.SocketMsg;
import jakarta.websocket.Session;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LiveRoomContainer {
    //以直播间的idz作为key,以直播间对应的用户集合作为value(UserId集合)

    private static final Map<Long, List<Long>> userIdMap=new ConcurrentHashMap<>();

    //以userId作为key,以每个用户的session会话对象作为value
    private static final Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 加入直播间
     * @param roomId
     * @param userId
     * @param seesion
     */
    public static void join(Long roomId,Long userId,Session seesion){
        //根据直播间id获取直播间用户列表
        List<Long> userIds = userIdMap.get(roomId);
        if (userIds==null){
            userIds = new ArrayList<>();
            userIdMap.put(roomId,userIds);
        }
        //把当前用户放入该直播间的用户列表
        userIds.add(userId);
        //把该用户session保存到map中
        sessionMap.put(userId,seesion);
    }

    /**
     * 离开直播间
     * @param roomId
     * @param userId
     */
    public static void leave(Long roomId,Long userId){
        List<Long> userIds = userIdMap.get(roomId);
        if (userIds==null){
            userIds=new ArrayList<>();
            userIdMap.put(roomId,userIds);
        }
        userIds.remove(userId);
        //把对应用户的session也进行删除
        sessionMap.remove(userId);
    }

    /**
     * 获取直播间的用户数量
     * @param roomId
     * @return
     */
    public static int getCount(Long roomId){
        List<Long> userIds = userIdMap.get(roomId);
        if (userIds==null){
            userIds=new ArrayList<>();
            userIdMap.put(roomId,userIds);
        }
        return userIds.size();
    }

    public static void sendMsg(SocketMsg msg){
        String msgType = msg.getMsgType();
        //如果是心跳信息,或者是无效信息,则之间结束
        if (msgType.equals(SocketMsg.MsgTypeEnum.HEART_BEAT.getCode())
                ||msgType.equals(SocketMsg.MsgTypeEnum.TOKEN_INVALID.getCode())){
            return;
        }
        //获取直播间的用户列表
        List<Long> userIds = userIdMap.get(msg.getLiveRoomId());
        if (CollectionUtils.isEmpty(userIds)){
            return;
        }
        //遍历直播间每一个用户id,转发消息
        userIds.forEach(userId -> {
            Session session = sessionMap.get(userId);//获取没一个用户的session
            if (session==null){
                return;
            }
            //推送消息
            session.getAsyncRemote().sendText(JSON.toJSONString(msg));
        });
    }
}
